package com.linkin.homepage.base.net;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.linkin.homepage.BuildConfig;
import com.linkin.homepage.util.JsonUtils;

import java.util.List;

public class ResponseList<T> implements IResponseData {

    public String msg = "";
    public int code = ERROR_PARSE_JSON;
    public int success = ERROR_TIME_OUT;
    public List<T> data = null;

    @Override
    public void setErrorCode(int errorCode) {
        this.code = errorCode;
    }

    @Override
    public int getErrorCode() {
        return code;
    }

    @Override
    public int getSuccessResponse() {
        return success;
    }

    @Override
    public void setMsg(String msg) {
        this.msg = msg;
    }

    @Override
    public boolean hasData() {
        return data != null && data.size() > 0;
    }

    static ResponseList fromJson(Gson gson, String json, Class clazz) {
        if (TextUtils.isEmpty(json)) {
            ResponseList response = new ResponseList();
            response.setMsg("数据异常");
            return response;
        }

        ResponseList response;
        try {
            response = (ResponseList) JsonUtils.fromJson(gson, json, ResponseList.class, clazz);
            if (response == null) {
                response = new ResponseList();
                response.setMsg("数据异常");
            }
        } catch (Exception e) {
            // for test
            if (BuildConfig.DEBUG) {
                if (clazz != null) {
                    JsonUtils.e("class:" + clazz.toString() + "\nerror:" + e.getMessage() + "\nstr:" + json);
                } else {
                    JsonUtils.e("error:" + e.getMessage() + "\nstr:" + json);
                }
            }

            response = new ResponseList();
            response.setMsg("数据异常");
        }
        return response;
    }
}